class ProductsController < ApplicationController
  before_filter :authenticate, :except => :show
  before_filter :admin_user, :except => [:show, :index]

  def new
    @title = t "product.new.title"
    @product = Product.new
    @product.active=true
    @categories = Category.find(:all)
  end

  def create
    @product = Product.new(params[:product])
    if @product.save
      flash[:success] = t "product.save.successfull"
      redirect_to @product
    else
      @title = t "product.new.title"
      @categories = Category.find(:all)
      render 'new'
    end
  end

  def show
    @product = Product.find(params[:id])
    @title = @product.name
    @category = Category.find_by_id(@product.category_id)
  end

  def edit
    @product = Product.find(params[:id])
    @title = t "product.edit.title"
    @categories = Category.find(:all)
  end

  def update
    @product = Product.find(params[:id])

    if @product.update_attributes(params[:product])
      flash[:success] = t "product.update.successfull"
      redirect_to @product
    else
      @title = t "product.edit.title"
      @categories = Category.find(:all)
      render 'edit'
    end
  end

  def destroy
    # TODO check if it is allowed to be deleted

    if CartItem.count(:all, :conditions => ['product_id = ?', params[:id]]) == 0 then
      Product.find(params[:id]).destroy

      flash[:success] = t "product.delete.successfull"
      redirect_to "/admin"
    else
      flash[:error] = t "product.delete.fail"
      redirect_to edit_product_path(params[:id])
    end
  end

  def index
    @products = Product.paginate(:page => params[:page])
  end

end